import { createAsyncThunk, createReducer, createSlice, PayloadAction } from "@reduxjs/toolkit"
import { RootState } from "..";
import { getListAsync } from "../../services/remoteService";

export interface ListType{
    isLoading: boolean,
    list: number[]
}

const initialState: ListType = {
    list: [],
    isLoading: true
}

const randomNumberSlice = createSlice({
    name: "list",
    initialState,
    reducers: {
        init(state, action: PayloadAction<Array<number>>) {
            console.log("init invoke")
            state.list = action.payload;
        },
        push(state) {
            state.list.push(Math.floor(Math.random() * 100));
        },
        pop(state, action:PayloadAction<number>){
            state.list.slice(action.payload, 1);
        }
    },
    extraReducers: builder=>{
        builder.addCase(initList.fulfilled, (state, action)=>{
            state.isLoading = false;
            state.list = action.payload;
        })
    }
});

export const { push, pop, init } = randomNumberSlice.actions;

export const selectList = (state: RootState) => state.randomNumberList.list;
export const selectIsLoading = (state: RootState) => state.randomNumberList.isLoading;

export const initList = createAsyncThunk(
    "list/init",
    async () => {
        const response = await getListAsync();
        return response.data;
    }
)

export const init2 = createReducer(initialState, builder=>{
    builder.addCase(initList.fulfilled, (state,action)=>{
        state.isLoading = false,
        state.list = action.payload
    });
});

export default randomNumberSlice.reducer;